package com.wsc.wisdomchina.activitity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.wsc.wisdomchina.R;
import com.wsc.wisdomchina.Tools.JsonTools;
import com.wsc.wisdomchina.Tools.Tools;
import com.wsc.wisdomchina.activitity.baseactivity.BaseActivity;
import com.wsc.wisdomchina.callback.ContributorView;
import com.wsc.wisdomchina.constant.Constant;
import com.wsc.wisdomchina.javaBean.LivingExpenseBean;
import com.wsc.wisdomchina.javaBean.OrderStrBean;
import com.wsc.wisdomchina.javaBean.PayResult;
import com.wsc.wisdomchina.javaBean.RespObj;
import com.wsc.wisdomchina.javaBean.SetupInputBean;
import com.wsc.wisdomchina.presenter.ContributorPresenter;
import com.wsc.wisdomchina.view.MyToast;

import java.util.Map;

/**
 * 生活缴费账户
 */
public class LivingExpensesDetailActivity extends BaseActivity implements View.OnClickListener,ContributorView {

    private TextView fragment_lyhd_title;//标题
    private ImageView fragment_lyhd_back;//返回按钮
    private Context context;
    private String itemId;
    private String projectId;
    private String countParam;
    private String cidNumber;
    private ContributorPresenter contributorPresenter;
    private final String HOMEITEMLISTFLAG="HOMEITEMLISTFLAG";
    private final String HOMEPAYFLAG="HOMEPAYFLAG";
    private Button bt_yuyue;
    private MyToast myToast;
    private TextView tv_payAmount;
    private TextView tv_danWei;
    private TextView tv_huHao;
    private TextView tv_huHaoName;
    private TextView tv_address;
    private TextView tv_balance;
    private TextView tv_month;
    private RelativeLayout layout_balance;
    private RelativeLayout layout_jine;
    private EditText et_jine;
    private TextView tv_poundage;
    private SetupInputBean setupInputBean;
    private RelativeLayout layout;
    private ScrollView scrollview;
    private String uid;
    private final int SDK_PAY_FLAG=0x12;
    private LinearLayout layout_progress;
    private ProgressBar pb_todayInfo;
    private RelativeLayout layout_address;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0x11:
                    final String order=(String) msg.obj;
                    Runnable payRunnable = new Runnable() {

                        @Override
                        public void run() {
                            PayTask alipay = new PayTask(LivingExpensesDetailActivity.this);
                            Map<String, String> result = alipay.payV2(order, true);
                            Message msg = new Message();
                            msg.what = SDK_PAY_FLAG;
                            msg.obj = result;
                            mHandler.sendMessage(msg);
                        }
                    };
                    Thread payThread = new Thread(payRunnable);
                    payThread.start();
                    break;
                case SDK_PAY_FLAG:
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();

                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        myToast.showShort("支付成功");
                        finish();
                    } else {
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            myToast.showShort("支付结果确认中");
                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            myToast.showShort("支付失败");
                        }
                    }
                    break;
                default:
                    break;
            }
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.liveexpensedetail_layout);
        context=this;
        myToast=new MyToast(context);
        contributorPresenter = new ContributorPresenter(this, context);
        Intent intent=getIntent();
        itemId=intent.getStringExtra("itemId");
        projectId=intent.getStringExtra("projectId");
        countParam=intent.getStringExtra("count");
        cidNumber=intent.getStringExtra("cidNumber");
        uid=Tools.getSharedPreferencesStrings(Constant.SharePreferenceUserid,"",context);
        initView();
        contributorPresenter.getHomeSetUpInput(projectId,countParam,itemId,cidNumber,HOMEITEMLISTFLAG);
    }

    private void initView() {
        layout_address=(RelativeLayout) findViewById(R.id.layout_address);
        fragment_lyhd_title=(TextView) findViewById(R.id.tv_headtitle);//标题
        fragment_lyhd_back=(ImageView) findViewById(R.id.regist_back);//返回按钮
        fragment_lyhd_back.setOnClickListener(this);
        fragment_lyhd_title.setText("账单详情");
        bt_yuyue=(Button) findViewById(R.id.bt_yuyue);
        bt_yuyue.setOnClickListener(this);
        tv_payAmount=(TextView) findViewById(R.id.tv_payAmount);
        tv_danWei=(TextView) findViewById(R.id.tv_danWei);
        tv_huHao= (TextView) findViewById(R.id.tv_huHao);
        tv_huHaoName=(TextView) findViewById(R.id.tv_huHaoName);
        tv_address=(TextView) findViewById(R.id.tv_address);
        tv_balance=(TextView) findViewById(R.id.tv_balance);
        tv_month=(TextView) findViewById(R.id.tv_month);
        layout_balance=(RelativeLayout) findViewById(R.id.layout_balance);
        layout_jine=(RelativeLayout) findViewById(R.id.layout_jine);
        et_jine=(EditText) findViewById(R.id.et_jine);
        tv_poundage=(TextView) findViewById(R.id.tv_poundage);
        scrollview=(ScrollView) findViewById(R.id.scrollview);
        layout=(RelativeLayout) findViewById(R.id.layout);
        layout_progress=(LinearLayout) findViewById(R.id.layout_progress);
        pb_todayInfo=(ProgressBar) findViewById(R.id.pb_todayInfo);
    }

    @Override
    public void onLoadContributorStart(String flag) {
        bt_yuyue.setEnabled(false);
        if(flag.equals(HOMEITEMLISTFLAG))
        {
            pb_todayInfo.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onLoadContributorSuccess(String jsonString, String flag) {
        try {
            //banner
            if (flag.equals(HOMEITEMLISTFLAG)) {
                RespObj respObj = JsonTools.jsonStringToObject(jsonString, RespObj.class);
                String code = respObj.getCode();
                Object object = respObj.getMessage();
                if (code.equals("200") && object != null) {
                    layout.setVisibility(View.GONE);
                    scrollview.setVisibility(View.VISIBLE);
                    String jsonMessage = JsonTools.objectToJsonString(object);
                    setupInputBean=JsonTools.jsonStringToObject(jsonMessage,SetupInputBean.class);
                    tv_payAmount.setText("¥ "+ setupInputBean.getPayAmount());
                    tv_danWei.setText(setupInputBean.getUnitName());
                    tv_huHao.setText(setupInputBean.getAccount());
                    tv_huHaoName.setText(setupInputBean.getCustomerName());
                    String address=setupInputBean.getCustomeAddress();
                    if(address==null || address.isEmpty())
                    {
                        layout_address.setVisibility(View.GONE);
                    }else {
                        layout_address.setVisibility(View.VISIBLE);
                        tv_address.setText(address);
                    }

                    String balance=setupInputBean.getBalance();
                    if(balance==null || balance.isEmpty())
                    {
                        layout_balance.setVisibility(View.GONE);
                    }else {
                        layout_balance.setVisibility(View.VISIBLE);
                        tv_balance.setText(setupInputBean.getBalance());
                    }
                    tv_month.setText(setupInputBean.getMonth());

                    String isOk=setupInputBean.getIsOk();
                    if(isOk.equals("1"))
                    {
                        layout_jine.setVisibility(View.VISIBLE);
                    }else {
                        layout_jine.setVisibility(View.GONE);
                    }

                    String poundage=setupInputBean.getPoundage();
                    if(poundage==null || poundage.isEmpty())
                    {
                        tv_poundage.setVisibility(View.GONE);
                    }else {
                        tv_poundage.setVisibility(View.VISIBLE);
                        String s="备注:每笔在线缴费手续费为每笔"+poundage+"元";
                        tv_poundage.setText(s);
                    }

                }else
                {
                    layout.setVisibility(View.VISIBLE);
                    scrollview.setVisibility(View.GONE);
                }

            }
            //生活缴费获取支付信息
            else if(flag.equals(HOMEPAYFLAG))
            {
                RespObj respObj = JsonTools.jsonStringToObject(jsonString, RespObj.class);
                String code = respObj.getCode();
                Object object = respObj.getMessage();
                if (code.equals("200") && object != null) {
                    String jsonMessage = JsonTools.objectToJsonString(object);
                    OrderStrBean orderStrBean = JsonTools.jsonStringToObject(jsonMessage, OrderStrBean.class);
                    String order=orderStrBean.getOrderStr();
                    Message msg = new Message();
                    msg.what = 0x11;
                    msg.obj = order;
                    mHandler.sendMessage(msg);
                }
            }

        } catch (Exception e) {

        }
    }

    @Override
    public void onLoadContributorComplete(String flag) {
        bt_yuyue.setEnabled(true);
        if(flag.equals(HOMEITEMLISTFLAG))
        {
            pb_todayInfo.setVisibility(View.GONE);
            layout_progress.setVisibility(View.GONE);
        }
    }

    @Override
    public void onLoadContributorError(String error, String flag) {
    }


    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.regist_back:
                finish();
                break;
            case R.id.bt_yuyue:
                try {

                    String isOk=setupInputBean.getIsOk();
                    String payAmount=setupInputBean.getPayAmount();//欠费金额
                    String poundage=setupInputBean.getPoundage();//手续费
                    if(isOk.equals("1"))
                    {
                        //支持预缴
                        String jiner=et_jine.getText().toString().trim();
                        if(jiner==null || jiner.isEmpty())
                        {
                            myToast.showShort("缴费金额不能为空");
                        }else {
                            Double jin=Double.parseDouble(jiner);
                            if(jin>1)
                            {
                                //TODO  发送缴纳接口
                                contributorPresenter.postHomePay(uid,Double.parseDouble(poundage),projectId,
                                        tv_huHao.getText().toString().trim(),tv_danWei.getText().toString().trim(),tv_month.getText().toString().trim(),
                                        tv_huHaoName.getText().toString().trim(),tv_address.getText().toString().trim(),
                                        cidNumber,jin,itemId,HOMEPAYFLAG);
                            }else {
                                myToast.showShort("缴费金额不能少于1元");
                            }
                        }

                    }else {
                        //不支持预缴
                        Double pay=Double.parseDouble(payAmount);
                        if(pay>0)
                        {
                            //TODO  发送缴纳接口
                            contributorPresenter.postHomePay(uid,Double.parseDouble(poundage),projectId,
                                    tv_huHao.getText().toString().trim(),tv_danWei.getText().toString().trim(),tv_month.getText().toString().trim(),
                                    tv_huHaoName.getText().toString().trim(),tv_address.getText().toString().trim(),
                                    cidNumber,pay,itemId,HOMEPAYFLAG);
                        }else {
                            myToast.showShort("您不需要缴费");
                        }
                    }

                }catch (Exception e)
                {
                    myToast.showShort("缴费失败");
                }
                break;
        }
    }

}
